package com.wangyh.edit.prettyedit.tree;

import com.wangyh.edit.prettyedit.constant.EditConstant;
import com.wangyh.edit.prettyedit.pages.PageFactory;
import com.wangyh.edit.prettyedit.util.FileImgUtils;
import com.wangyh.edit.prettyedit.util.PreferencesUtils;
import com.wangyh.edit.prettyedit.mainframe.MainFrameView;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.control.Alert;
import javafx.scene.control.TreeCell;
import javafx.scene.input.MouseEvent;
import javafx.scene.text.Text;
import org.apache.commons.io.FileUtils;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.Clipboard;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 左侧树，构造文件目录
 * @author wangyh
 */
public class LeftTreeView {

    boolean flag = false;
    /**
     * 构造左侧树
     * @return
     */
    public TreeView getTree(){
        //保存工作区间
        String workdir = PreferencesUtils.getPreferences(EditConstant.storeConfig, EditConstant.sessionUser + "workspace", "");
        if(workdir==null || workdir.trim().length()==0){
            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.setContentText(null);
            alert.setTitle("提示！");
            alert.setHeaderText("当前未设置工作目录，请选择文件树->设置工作空间");
            alert.show();

//            DirectoryChooser dir_chooser = new DirectoryChooser();
//            dir_chooser.setTitle("选择文件存储的路径");
//            // get the file selected
//            File file = dir_chooser.showDialog(mainFrameView.getWindow());
//            if (file != null) {
//                System.out.println(file.getAbsolutePath() + "  selected");
//
//                //保存工作区间
//                PreferencesUtils.setPreferences(EditConstant.storeConfig, EditConstant.sessionUser + "workspace", file.getAbsolutePath());
//
//                //重新构造树
//                mainFrameView.generateTree();
//            }
            return null;
        }

        //构建树控件
        TreeView<File> tree = generateTreeView(workdir);

//        tree.editableProperty().addListener(new InvalidationListener() {
//            @Override
//            public void invalidated(Observable observable) {
//
//            }
//        });

        //鼠标点击事件，虽然之前选中，但是别的菜单把右侧已替换。
        tree.addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
            public void handle(MouseEvent event) {
                if(flag){
                    flag = false;
                    return;
                }
                Node node = event.getPickResult().getIntersectedNode();
                TreeItem no = (TreeItem)tree.getSelectionModel().getSelectedItem();
//                tree.edit(no);

                if (node instanceof Text || (node instanceof TreeCell && ((TreeCell) node).getText() != null)) {
                    File file = (File) ((TreeItem)tree.getSelectionModel().getSelectedItem()).getValue();
//                    System.out.println("Node click: " + file.getAbsolutePath());

                    //具体的点击事件处理
                    TreeClick.clickNode(file,tree);
                }
            }
        });

        //响应Ctrl V 复制文件
        setCtrlVEvent(tree);

        //树节点变更事件，在删除结点的时候会用到
        tree.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() {
            @Override
            public void changed(ObservableValue observable, Object oldValue, Object newValue) {
                TreeItem<File> currentSelectItem = (TreeItem<File>) newValue;

                File file = (File) ((TreeItem)tree.getSelectionModel().getSelectedItem()).getValue();
//                System.out.println("Node change: " + file.getAbsolutePath());

                flag = true;
                //具体的点击事件处理
                TreeClick.clickNode(file,tree);
            }
        });

        return tree;
    }

    /**
     * 构造树控件，根节点
     * @param workdir
     * @return
     */
    private TreeView generateTreeView(String workdir){
        //如果路径不存在，则创建路径
//        File file = new File(workdir + File.separator + EditConstant.sessionUser);
        File file = new File(workdir);
        if(!file.exists()){
            file.mkdirs();
        }

        //定义一个图片类型节点对象 - 根
        ImageView rootIcon = new ImageView(
                new Image(MainFrameView.class.getResourceAsStream("/img/pc2.png"))
        );
        rootIcon.setFitHeight(EditConstant.treeIconHeight);
        rootIcon.setFitWidth(EditConstant.treeIconWeight);

        //定义树结构模型中的一个选项(跟选项节点挂载前文定义的图形节点)
        TreeItem<File> rootItem = new FileTreeItem(file,rootIcon);
        //设置节点选择项是否可以展开，本例中为可展开
        rootItem.setExpanded(true);

        //创建一个树形视图组件
        TreeView<File> tree = new TreeView<File>(rootItem);
//        tree.getStyleClass().add("file-tree-view");
        tree.setPrefWidth(280);
        tree.setEditable(true);
        tree.setCellFactory((TreeView<File> p) -> new FileTreeCellImpl(tree,EditConstant.mainFrameView));

        return tree;
    }

    /**
     * 响应Ctrl V 复制文件
     * @param tree
     */
    private void setCtrlVEvent(TreeView<File> tree){
        tree.addEventFilter(KeyEvent.KEY_RELEASED, new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent keyEvent) {
                //Ctrl + V ，相应粘贴事件
                System.out.println("edit:" + tree.getEditingItem());
                if(keyEvent.isControlDown() && keyEvent.getCode().getName().equals("V")){
                    File file = (File) ((TreeItem)tree.getSelectionModel().getSelectedItem()).getValue();
                    if(!file.isDirectory()){
                        Alert alert = new Alert(Alert.AlertType.WARNING);
                        alert.setContentText("请选择文件目录结点进行文件复制！");
                        alert.setTitle("复制失败！");
                        alert.setHeaderText("提示！");
                        alert.show();
                        return;
                    }

                    Clipboard clipboard = Clipboard.getSystemClipboard();
                    List<File> files = clipboard.getFiles();
                    if(files==null || files.size()==0){
                        Alert alert = new Alert(Alert.AlertType.WARNING);
                        alert.setContentText("当前无文件复制！请先复制文件或文件夹");
                        alert.setTitle("复制失败！");
                        alert.setHeaderText("提示！");
                        alert.show();
                        return;
                    }

                    // destDir is a File, the target directory.
                    for (File oldFile : files) {
                        System.out.println(oldFile.getAbsolutePath());
                        if (oldFile.isDirectory()) {
                            try {
                                FileUtils.copyDirectoryToDirectory(oldFile, file);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        } else {
                            try {
                                FileUtils.copyFileToDirectory(oldFile, file);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    tree.getSelectionModel().getSelectedItem().getChildren().clear();
                    //更新儿子
                    for(final File sonfile: tree.getSelectionModel().getSelectedItem().getValue().listFiles()){
                        if(sonfile.isDirectory()){
                            ImageView folderIcon = new ImageView(
                                    new Image(MainFrameView.class.getResourceAsStream("/img/folder.png"))
                            );
                            folderIcon.setFitHeight(EditConstant.treeIconHeight);
                            folderIcon.setFitWidth(EditConstant.treeIconWeight);
                            tree.getSelectionModel().getSelectedItem().getChildren().add(new FileTreeItem(sonfile,folderIcon));
                        }else{
                            //设置图标
                            ImageView fileIcon = FileImgUtils.getFileImageView(sonfile);
                            tree.getSelectionModel().getSelectedItem().getChildren().add(new FileTreeItem(sonfile,fileIcon));
                        }
                    }
                    //复制完，该节点需要展开。
                    tree.getSelectionModel().getSelectedItem().setExpanded(true);
                }

            }
        });
    }

}
